<template>
    <div class="chart-container">
        <canvas ref="chartCanvas"></canvas>
    </div>
</template>



<script>
import Chart from 'chart.js'; // 自动引入所有图表类型‌:ml-citation{ref="1,6" data="citationList"}

export default {
    name: 'chart-component',
    props: {
        chartData: { type: Object, required: true }, // 数据源
        chartOptions: { type: Object, default: () => ({}) } // 配置项
    },
    watch: {
        chartData(newId, oldId) {
            if (newId !== oldId) {
                if (this.chartInstance) {
                    this.chartInstance.data = newId;
                    this.chartInstance.update();
                }
            }
        },
        // chartData: {
        //     deep: true,
        //     handler() {
        //         if (this.chartInstance) {
        //             this.chartInstance.data = this.chartData;
        //             this.chartInstance.update();
        //         }
        //     }
        // }
    },
    data() {
        return {
            loading: false,
            chartInstance: null

        }
    },
    created() {

    },
    mounted() {
        this.initChart();
        window.addEventListener('resize', this.handleResize)
    },
    beforeDestroy() {
        if (this.chartInstance) this.chartInstance.destroy(); // 销毁实例防止内存泄漏‌:ml-citation{ref="5,8" data="citationList"}
        window.removeEventListener('resize', this.handleResize)
    },
    methods: {
        goBack() {
            console.log('go back');
        },
        initChart() {
            const ctx = this.$refs.chartCanvas.getContext('2d');
            this.chartInstance = new Chart(ctx, {
                type: this.chartData.type || 'bar', // 默认柱形图
                data: this.chartData,
                options: this.chartOptions
            });
        },
        handleResize() {
            if (this.chartInstance) this.chartInstance.resize();
        }

    }
}

</script>

<style scoped>
.chart-container {
    width: 100%;
    min-height: 300px;
}
</style>
